package service

import (
	"course/basic/config"
	"course/handler/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"strconv"
	"sync"
)

var (
	upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}
	clients = map[string]*Node{}
	mu      sync.Mutex
)

type Node struct {
	UserId string
	Conn   *websocket.Conn
	Data   chan []byte
}

func Chat(c *gin.Context) {
	userId := c.Query("userId")
	friendId := c.Query("friendId")
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	mu.Lock()
	clients[userId] = &Node{
		UserId: userId,
		Conn:   conn,
		Data:   make(chan []byte, 100),
	}
	mu.Unlock()
	go ReceiverMsg(clients[userId], friendId)
	go SenderMsg(clients[userId])
}
func ReceiverMsg(myNode *Node, friendId string) {
	for {
		_, data, err := myNode.Conn.ReadMessage()
		if err != nil {
			return
		}
		fmt.Println("接收", data)
		fmt.Println(string(data))
		friendNode := clients[friendId]
		friendNode.Data <- data
		var chat model.Chat
		userId, _ := strconv.Atoi(myNode.UserId)
		id, _ := strconv.Atoi(friendId)
		chat.UserId = userId
		chat.FriendId = id
		chat.Content = string(data)
		err = chat.AddChat(config.DB)
		if err != nil {
			log.Fatal("./log")
			return
		}
	}
}
func SenderMsg(myNode *Node) {
	for {
		select {
		case data := <-myNode.Data:
			fmt.Println("发送", data)
			err := myNode.Conn.WriteMessage(websocket.TextMessage, data)
			var chat model.Chat
			userId, _ := strconv.Atoi(myNode.UserId)
			chat.UserId = userId
			chat.Content = string(data)
			err = chat.AddChat(config.DB)
			if err != nil {
				return
			}

		}
	}
}
